package main

import (
	// "github.com/fsnotify/fsnotify"
	"io"
	"log"
	"os"
	"path"
	"strconv"
	"strings"

	"github.com/radu-munteanu/fsnotify"
)

func main() {
	//创建一个监控对象
	watch, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watch.Close()
	//添加要监控的对象，文件或文件夹
	sendfilespath := "/root/sendfiles"
	err = watch.Add(sendfilespath)
	log.Println("开始监控文件夹：" + sendfilespath)
	//	filespath := "/root/files"
	if err != nil {
		log.Fatal(err)
	}
	//我们另启一个goroutine来处理监控对象的事件
	go func() {
		for {
			select {
			case ev := <-watch.Events:
				{
					if ev.Op&fsnotify.Update == fsnotify.Update {
						log.Println("新文件 : ", ev.Name)

						filesize := GetFileSize(ev.Name)

						log.Println("文件大小：" + filesize)
						log.Println("文件后缀名：" + GetFileSuffix(ev.Name))
						err := os.Remove(ev.Name) //删除文件
						if err != nil {
							//如果删除失败则输出 file remove Error!
							log.Println("文件移除错误!")
							//输出错误详细信息
							log.Println("%s", err)
						} else {
							//如果删除成功则输出 file remove OK!
							log.Println("文件移除成功!")
						}
					}
				}
			case err := <-watch.Errors:
				{
					log.Println("error : ", err)
					return
				}
			}
		}
	}()

	//循环
	select {}
}

func GetFileSize(filename string) string {
	//文件大小
	fileInfo, _ := os.Stat(filename)
	filesize := fileInfo.Size() //返回的是字节
	return strconv.FormatInt(filesize, 10)
	/*
		#string到int
		int,err:=strconv.Atoi(string)
		#string到int64
		int64, err := strconv.ParseInt(string, 10, 64)
		#int到string
		string:=strconv.Itoa(int)
		#int64到string
		string:=strconv.FormatInt(int64,10)
	*/

}

func GetFileSuffix(filename string) string {
	fileSuffix := path.Ext(filename) //获取文件后缀
	fileSuffix = strings.Replace(fileSuffix, ".", "", -1)
	return fileSuffix
}

func CopyFile(dstName, srcName string) (written int64, err error) {
	src, err := os.Open(srcName)
	if err != nil {
		return
	}
	defer src.Close()
	dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		return
	}
	defer dst.Close()
	return io.Copy(dst, src)
}
